package com.tian.user.exception;

import com.alibaba.fastjson.JSON;
import com.tian.common.AuthResultCode;
import com.tian.common.result.BaseResult;
import com.tian.common.result.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * <pre>
 *     自定义无权限异常
 * </pre>
 * @author zhump
 */
@Component
public class AccessDeniendHandlerException implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        AuthResultCode resultCode = AuthResultCode.NO_PERMISSION;
        BaseResult<Object> result = Result.wrap(resultCode.getCode(),resultCode.getMsg());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(result));

    }
}
